import { asyncRoutes, constantRoutes } from '@/router'
import { renderMenu } from '@/api/default-apis'

// import { getProcess, getAllLine, getConfigAll } from '@/api/conf'
// import Layout from '@/layout'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => {
      return route.meta.roles.includes(role)
    })
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  // console.log('res', res)
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  // *** actions方法只能接受一个参数，因此传多个参数时，需包装成对象
  generateRoutes({ commit }, { roles, pid, isRerender }) {
    return new Promise(resolve => {
      // console.log('generateRoutes asyncRoutes', asyncRoutes)
      // console.log('generateRoutes isRerender', isRerender)
      // console.log('generateRoutes roles', roles)
      // console.log('generateRoutes pid', pid)
      // ***不能直接修改asyncRoutes，需复制一份，使用concat浅拷贝，可影响原数组(asyncRoutes)
      let asyncRoutesCopy = [].concat(asyncRoutes)
      if (isRerender) { // *** 是否需要重新请求menu, 当点击制程一级菜单时，为true
        asyncRoutesCopy = []
      }
      // console.log('generateRoutes asyncRoutesCopy', asyncRoutesCopy)
      // 调用 renderMenu 方法，生成动态路由list
      renderMenu(asyncRoutesCopy, pid, isRerender, roles).then(res => {
        let accessedRoutes
        // console.log('renderMenu roles', roles)
        if (roles.includes('SuperAdmin')) {
          accessedRoutes = asyncRoutesCopy || []
        } else {
          accessedRoutes = filterAsyncRoutes(asyncRoutesCopy, roles)
        }
        // console.log('accessedRoutes', accessedRoutes)
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
